﻿
	$G.localstorage = function (key, value) {
		return $G.localstorage.impl.init(key, value);
	};

	$G.localstorage.setItem = function (key, value, expirationSeconds) {
		return $G.localstorage.impl.setItem(key, value, expirationSeconds);
	};

	$G.localstorage.getItem = function (key) {
		return $G.localstorage.impl.getItem(key);
	};

	$G.localstorage.extendExpiration = function (key, seconds) {
		return $G.localstorage.impl.extendExpiration(key, seconds);
	}

	$G.localstorage.deleteItem = function (key) {
		return $G.localstorage.impl.deleteItem(key);
	};

	$G.localstorage.impl = {

		ls: window.localStorage,

		init: function (key, value) {
			if (typeof value != 'undefined') {
				return this.setItem(key, value);
			} else {
				return this.getItem(key);
			}
		},

		setItem: function (key, value, expirationSeconds) {
			var expDate = new Date();

			if (typeof expirationSeconds !== 'undefined' && expirationSeconds > 0) {
				expDate.setTime(expDate.getTime() + expirationSeconds * 1000);
				expDate = expDate.getTime();
			}
			else
				expDate = 0;

			var item = JSON.stringify({ val: JSON.stringify(value), expirationSeconds: expirationSeconds, expires: expDate });

			this.ls.setItem(key, item);

			return this.parseResult(item);
		},

		getItem: function (key) {
			var lsitem = this.getRawItem(key);
			var ret = null;
			if (lsitem) {
				ret = this.parseResult(lsitem.val);
			}

			return ret;
		},

		getRawItem: function (key) {
			var item = this.ls.getItem(key);
			if (item) {
				item = JSON.parse(item);
				if (item.expires != 0) {
					var date = new Date();
					var curms = date.getTime();
					if (item.expires < curms) {
						//expired
						this.ls.removeItem(key);
						return null;
					}
				}
			}

			return item;
		},

		extendExpiration: function (key, seconds) {
			var item = this.getRawItem(key)
			if (item) {
				var s = typeof seconds === 'undefined' ? item.expirationSeconds : seconds;
				var value = this.parseResult(item.val);
				return this.setItem(key, value, s);
			}

			return null;
		},

		deleteItem: function (key) {
			this.ls.removeItem(key);
		},

		parseResult: function (res) {
			var ret;

			try {
				ret = JSON.parse(res);
				if (typeof ret === 'undefined') ret = res;
				if (ret == 'true') ret = true;
				else if (ret == 'false') ret = false;
				else {
					var f = parseFloat(ret);
					if (f == ret && typeof ret != 'object') ret = f;
				}
			}
			catch (e) { ret = res; }

			return ret;
		}
	}
